<!-- 知识库创建类型 -->
<template>
  <el-dialog
    class="dialogAdapter"
    :destroy-on-close="true"
    @close="handleClose"
    style="border-radius: 10px"
    v-model="props.visible"
    :title="`${!type ? '创建' : '编辑'}知识`"
  >
    <!--知识库from -->
    <el-form ref="ruleFormRef" :model="d.form" label-position="top">
      <div class="avatar-uploader">
        <img :src="base_2" class="avatar" />
      </div>

      <el-form-item prop="name" label="知识名称" :rules="[{ required: true, message: '请输入知识名称' }]">
        <el-input v-model="d.form.name" autocomplete="off" placeholder="请输入知识名称" />
      </el-form-item>
      <el-form-item label="知识描述">
        <el-input v-model="d.form.info" type="textarea" placeholder="请输入知识描述" />
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button v-if="!type" type="danger" @click="submitForm(ruleFormRef)"> 创建 </el-button>
        <!-- <el-button v-else type="danger" @click="submitEditForm(ruleFormRef)">
          编辑
        </el-button> -->
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { apIknowledSave } from "@/api/interface"
import base_2 from "@/assets/docs/base_2.svg"
import { ElMessage, FormInstance } from "element-plus"
import pubsub from "pubsub-js"
import { onMounted, reactive, ref } from "vue"

interface Props {
  editData?: any
  type?: string
  visible: boolean
}

const emits = defineEmits(["editDpData", "close"])
const props = defineProps<Props>()
const ruleFormRef = ref()

// 云模型from
const d = reactive({
  form: {
    name: "",
    info: ""
  }
})

// 清空数据
const dfData = {
  name: "",
  info: ""
}

onMounted(() => {
  console.log("props.editData", props.editData)
  if (props.editData && props.type) {
    d.form = props.editData
  }
})

// 创建提交
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      let { code } = await apIknowledSave(d.form)
      if (code === 200) {
        pubsub.publish("KNOWLEDCREATE")
        handleClose()
        ElMessage({
          type: "success",
          message: "添加成功"
        })
        d.form = dfData
      }
    } else {
      console.log("error submit!")

      return false
    }
  })
}

const handleClose = () => {
  emits("close")
}
// 编辑提交
// const submitEditForm = (formEl: FormInstance | undefined) => {
//   if (!formEl) return
//   formEl.validate(async (valid) => {
//     if (valid) {
//       console.log(valid, d.form, 'submit!')
//       let { code, data } = await apIknowledSave(d.form)
//       if (code === 1000) {
//         emits('editDpData', { ...d.form, ...data })
//       }
//     } else {
//       console.log('error submit!')
//       return false
//     }
//   })
// }
</script>
<style lang="scss" scoped>
.avatar-uploader {
  text-align: center;
  margin-bottom: 20px;
}
</style>
